package cn.itcast.service.impl;

import cn.itcast.dao.AreaDao;
import cn.itcast.domain.Area;
import cn.itcast.service.AreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

@Service
public class AreaServiceImpl implements AreaService {
    @Autowired
    private AreaDao areaDao;
    @Override
    @Transactional
    public void saveAll(List<Area> areas) {
        areaDao.saveAll(areas);
    }

    @Override
    @Transactional
    public void save(Area area) {
        areaDao.save(area);
    }

    @Override
    public Page<Area> pageQuery(Area area,int page, int rows) {
        PageRequest pageRequest = PageRequest.of(page-1, rows);
        ExampleMatcher exampleMatcher = ExampleMatcher.matching().withMatcher("province", ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("city", ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("district", ExampleMatcher.GenericPropertyMatchers.contains());


        Page<Area> page1 = areaDao.findAll(Example.of(area, exampleMatcher), pageRequest);
        return page1;
    }

    @Override
    @Transactional
    public void delete(List<String> ids) {
        for (String id : ids) {
            areaDao.deleteById(id);
        }
    }

    @Override
    public Area findById(String id) {

        Optional<Area> optional = areaDao.findById(id);
        if(optional.isPresent()){
            return optional.get();
        }
        return null;
    }

    @Override
    public List<Area> findAll() {
        List<Area> areas = areaDao.findAll();
        return areas;
    }


}
